package ClientSide;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JSeparator;
import javax.swing.JList;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.ListSelectionModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JCheckBox;

/**
 * @author Avishai Kopeliansky 
 * @ID 066717752
 * @author David Shimshon
 * @ID 038185617
 */
public class ClientWindow extends JFrame {

	/**
	 * Main Client Chat window
	 */
	private static final long serialVersionUID = -2201756895162568152L;
	private JPanel contentPane;
	private JTextField textField;
	private JTextArea textArea;
	private JList<String> list;
	private String uname,saddress,port;
	private JButton btnConnect, dcbutton;
	private Client c;
	private JCheckBox chckbxPersonalMessage;
	private boolean PM = false;
	/**
	 * Launch the application.
	 */
	public static void main(@SuppressWarnings("javadoc") String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ClientWindow frame = new ClientWindow("Avis","localhost","9999");
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame with details taken from the Cr3edentials screen.
	 * @param name Nickname
	 * @param address Server Address
	 * @param port Server Port
	 */
	public ClientWindow(String name, String address,String port) {
		setTitle("Chat Window");
		initialize();
		this.uname = name;
		this.saddress = address;
		this.port = port;
	}

	private void initialize(){
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 997, 615);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);

		JSeparator separator = new JSeparator();


		textField = new JTextField();
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent arg0) {
				//whenever enter is pressed and the textField isnt empty, it means there's an output to send
				if(arg0.getKeyCode() == KeyEvent.VK_ENTER && textField.getText().length() > 0)
				{
					String t = textField.getText();
					String n = "";					
					if( (n = list.getSelectedValue()) != null && PM){						
						c.writeMsg(t, n);
						textArea.append("PM->"+n+"<-:"+textField.getText()+"\r\n");
					}
					else {
						c.writeMsg(t);
					}
					textField.setText("");
				}
			}
		});
		textField.setEditable(false);
		textField.setColumns(10);

		JScrollPane scrollPane = new JScrollPane();

		btnConnect = new JButton("Connect");
		btnConnect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				c = new Client (uname,saddress,port,textArea,list);
				textArea.append("Connecting \r\n");
				new Thread(){
					public void run(){
						c.initMe();
						if(!c.isOk())
						{
							//case the connection failed
							textArea.append("error connecting to "+saddress+" !\n");

						}
						else
						{
							//case the connection succeeded
							c.auth();
							c.start();
							try {
								Thread.sleep(100L);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if(c.getFlag()){
							btnConnect.setEnabled(false);
							textField.setEditable(true);
							dcbutton.setEnabled(true);
							
							}
							else 
							{
								textArea.append("Please change your credentials and try again\n");
							}

						}
					}

				}.start();


			}
		});

		JScrollPane scrollPane_1 = new JScrollPane();

		dcbutton = new JButton("Disconnect");
		dcbutton.setEnabled(false);
		dcbutton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				c.close();
				textField.setEditable(false);
				while(c.isAlive()){};
				textArea.append("Disconnected\n");
				btnConnect.setEnabled(true);
				dcbutton.setEnabled(false);
				DefaultListModel<String> dlm = new DefaultListModel<String>();
				list.setModel(dlm);
			}
		});

		chckbxPersonalMessage = new JCheckBox("Personal Message");
		chckbxPersonalMessage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(!PM){
					PM = true;
				}
				else
					PM = false;
			}
		});

		JButton btnChangeData = new JButton("Change Data");
		btnChangeData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				new Credentials().setVisible(true);
				dispose();
			}
		});
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
				gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
						.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
								.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE)
								.addGroup(gl_contentPane.createSequentialGroup()
										.addContainerGap()
										.addComponent(separator, GroupLayout.PREFERRED_SIZE, 799, GroupLayout.PREFERRED_SIZE)
										.addGap(18))
										.addGroup(gl_contentPane.createSequentialGroup()
												.addComponent(textField, GroupLayout.DEFAULT_SIZE, 818, Short.MAX_VALUE)
												.addGap(6))
												.addGroup(gl_contentPane.createSequentialGroup()
														.addContainerGap()
														.addComponent(chckbxPersonalMessage, GroupLayout.PREFERRED_SIZE, 102, Short.MAX_VALUE)
														.addGap(49)
														.addComponent(btnChangeData, GroupLayout.PREFERRED_SIZE, 84, Short.MAX_VALUE)
														.addGap(531)))
														.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
																.addGroup(gl_contentPane.createSequentialGroup()
																		.addPreferredGap(ComponentPlacement.RELATED)
																		.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))
																		.addGroup(gl_contentPane.createSequentialGroup()
																				.addGap(12)
																				.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
																						.addComponent(btnConnect, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)
																						.addComponent(dcbutton, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
																						.addGap(40)))
																						.addContainerGap())
				);
		gl_contentPane.setVerticalGroup(
				gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
						.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
								.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE)
								.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE))
								.addGap(11)
								.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
										.addGroup(gl_contentPane.createSequentialGroup()
												.addComponent(separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(textField, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
												.addPreferredGap(ComponentPlacement.UNRELATED)
												.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
														.addComponent(chckbxPersonalMessage, GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
														.addComponent(btnChangeData, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
														.addGroup(gl_contentPane.createSequentialGroup()
																.addPreferredGap(ComponentPlacement.RELATED)
																.addComponent(btnConnect)
																.addPreferredGap(ComponentPlacement.RELATED)
																.addComponent(dcbutton)))
																.addContainerGap())
				);

		list = new JList <String>();
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollPane_1.setViewportView(list);

		textArea = new JTextArea();
		textArea.setEditable(false);
		textArea.setWrapStyleWord(true);
		textArea.setCaretPosition(textArea.getDocument().getLength());
		scrollPane.setViewportView(textArea);
		contentPane.setLayout(gl_contentPane);
	}
}
